// app.ts
import { Application, IBoot } from 'egg';
import { Strategy } from 'passport-local';
export default class FooBoot implements IBoot {
    private readonly app: Application;

    constructor(app: Application) {
        this.app = app;
    }
    configDidLoad() {
        // Config, plugin files have loaded.
        let { app } = this;
        //这个其实是在配置鉴权的方式，配置鉴权的
        app.passport.use(new Strategy({
            usernameField: 'userName', //从请求体里的哪个字段取到用户名
            passReqToCallback: true,//向callback中传递request对象
        }, async (request, userName, password, done) => {
            //SELECT * FROM user WHERE userName=? AND password=? limit 1
            let user = await app.mysql.get('user', { userName, password });
            console.log('user', user);
            //根据用户ID查询它的角色
            if (user) {
                let roles = await app.mysql.query(`SELECT role.* FROM role_user INNER JOIN role ON role_user.role_id=role.id WHERE role_user.user_id=?`, [user.id]);
                user.roles = roles.map(item => item.name);
                console.log('user', user);
                done(null, user);
            } else {
                //如果登录失败了，则需要清除掉原来的登录状态
                request.ctx.logout();
                done(null, false);
            }
        }));
    }
}
/**
 * 现在实现鉴权 passport
 *
 */